<?php
class MessagesController extends AppController {
    var $name = 'Messages';
    var $uses = array('Message', 'User');
    
    function add($target = null) {
        if ($this->Auth->user('role') != 'admin') {
            $this->User->id = $this->Auth->user('id');
            $from_user = $this->User;
            
            $this->User->id = $target;
           $to_user = $this->User;
        
            if ($this->data) {
                $this->Message->create();
                $this->Message->save($this->data);
                $this->Message->save(array('time' => date('Y-m-d H:i:s'),
                'unread' => True,
                'from_id' => $from_user->field('id'),
                'from_name' => $from_user->StudentProfile ? $from_user->StudentProfile->field('real_name') : $from_user->TeacherProfile->field('real_name'),
                'to_id' => $to_user->field('id'),
                'to_name' => $to_user->StudentProfile ? $to_user->StudentProfile->field('real_name') : $to_user->TeacherProfile->field('real_name'));
            }
        }
        else {
            $this->Session->setFlash("管理员不能参与交流");
            $this->redirect(array('controller' => 'users', 'action' => 'login'));
        }
    }
    
    function view($id = null) {
        $this->Message->id = $id;
        if ($this->Auth->user('id') == $this->Message->field('to_id')) {
            $this->set('data', $this->Message->read());
        }
        else {
            $this->Session->setFlash("您没有相应的权限");
            $this->redirect(array('controller' => 'users', 'action' => 'login'));
        }
    }
    
    
}
?>